class Lib {
    heartbeatInterval
    heartbeat

    constructor(roomId) {
        this.wws_url = 'wss://danmuproxy.douyu.com:8503/'
        this.heartbeat = this.encode('type@=mrkl/')
        this.heartbeatInterval = 45000
        this.roomId = roomId

    }


    get_ws_info() {
        let reg_datas = []
        let data = this.encode(`type@=loginreq/roomid@=${this.roomId}`)
        reg_datas.push(data)
        data = this.encode(`type@=joingroup/rid@=${this.roomId}/gid@=-9999/`)
        reg_datas.push(data)
        return {ws_url: this.wws_url, login_data: reg_datas}
    }

    decode(result) {
        const sliced = result.slice(12).toString();
        // 减二删掉最后的'/'和'\0'
        const splited = sliced.substring(0, sliced.length - 2).split('/');
        const map = this.formatDanmu(splited);
        return map
    }

    formatDanmu(msg) {
        let map = {};
        for (let i in msg) {
            let splited = msg[i].split('@=');
            map[splited[0]] = splited[1];
        }
        return map;
    }


    encode(content) {
        let data = Buffer.alloc(content.length + 13);
        data.writeInt32LE(content.length + 9, 0);
        data.writeInt32LE(content.length + 9, 4);
        data.writeInt32LE(689, 8);
        data.write(content + '\0', 12);
        return data
    }
}

exports = module.exports = Lib;